package com.info.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 计算文件中有多少行代码
 * @author 90711
 * @param count 总行数
 * @param explainCount 总注释数
 * @param blank 总空白数
 */
public class MyCount
{
	private static int count = 0;
	private static int explainCount = 0;
	private static int start = 0;
	private static int reStart = 0;
	private static int blank = 0;

	public static void main(String[] args)
	{
		
		String path = "G:\\eclipse源文件";
		File file = new File(path);
		conunt(file);
		System.out.println("你总共码了" + count + "行代码");
		System.out.println("其中有" + explainCount + "行注释");
		System.out.println("其中有" + blank + "空行");
		System.out.println("有效代码:" + (count - explainCount - blank) + "行");
	}

	/**
	 * @param file
	 */
	public static void conunt(File file)
	{
		if (file.isDirectory())
		{
			File[] listFiles = file.listFiles();

			for (int i = 0; i < listFiles.length; i++)
			{
				if (!listFiles[i].isDirectory() && listFiles[i].getName().endsWith(".java"))
				{
//					System.out.println(listFiles[i].getName());
					justCount(listFiles[i]);
				} else
				{
					conunt(listFiles[i]);
				}
			}
		} else
		{
			if (file.getName().endsWith(".java"))
			{
				justCount(file);
			}

		}
	}

	static void justCount(File file)
	{
		System.out.println(file.getName());
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader bfr = null;
		String line = "";
		try
		{
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, "UTF-8");
			bfr = new BufferedReader(isr);
			while ((line = bfr.readLine()) != null)
			{
				if (line.trim().isEmpty())
				{
					blank++;
				}
				if (line.trim().startsWith("//"))
				{
					explainCount++;
				} else
				{
					if (line.trim().startsWith("/*"))
					{
						start = count;
						reStart = blank;
					}
					if (line.trim().endsWith("*/") )
					{
						/**
						 * 取两个注释中间差，获取多行注释的行数
						 */
						start = count - start + 1;
						explainCount += start;
						blank = reStart;
					}
				}
				count++;
			}
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if (bfr != null)
				{
					bfr.close();
					bfr = null;
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}